/*******************************************************************************
 * Copyright (c) 2000, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package cuongnh.project.japanesediary.vocabulary.ui.editor.vocabulary.page.category;

import java.util.Set;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.Section;

import cuongnh.project.japanesediary.vocabulary.application.Activator;
import cuongnh.project.japanesediary.vocabulary.common.CommonServices;
import cuongnh.project.japanesediary.vocabulary.common.CommonUtils;
import cuongnh.project.japanesediary.vocabulary.model.Category;
import cuongnh.project.japanesediary.vocabulary.model.Vocabulary;
import cuongnh.project.japanesediary.vocabulary.ui.dialog.AddRelatedVocabularyDialog;
import de.ralfebert.rcputils.tables.TableViewerBuilder;

/**
 * @author dejan
 * 
 *         To change the template for this generated type comment go to Window -
 *         Preferences - Java - Code Generation - Code and Comments
 */
public class VocabularyCategoryDetailsPage implements IDetailsPage {
	private DataBindingContext m_bindingContext;
	private IManagedForm mform;
	private Section sctnNewSection;
	private Category currentCategory;
	private Table table;
	private TableViewer tableViewer;
	private TableViewerBuilder vocabularyList;
	private CommonServices commonServices;
	
	public VocabularyCategoryDetailsPage(
			CommonServices commonServices) {
		this.commonServices = commonServices;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.IDetailsPage#initialize(org.eclipse.ui.forms.
	 * IManagedForm)
	 */
	public void initialize(IManagedForm mform) {
		this.mform = mform;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.forms.IDetailsPage#createContents(org.eclipse.swt.widgets
	 * .Composite)
	 */
	public void createContents(Composite parent) {
		parent.setLayout(new GridLayout(1, false));

		sctnNewSection = mform.getToolkit().createSection(parent,
				Section.EXPANDED | Section.TITLE_BAR);
		sctnNewSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		mform.getToolkit().paintBordersFor(sctnNewSection);
		sctnNewSection.setText("Category:");
		createCategoryToolBar(sctnNewSection);

		Composite composite = new Composite(sctnNewSection, SWT.NONE);
		mform.getToolkit().adapt(composite);
		mform.getToolkit().paintBordersFor(composite);
		sctnNewSection.setClient(composite);
		composite.setLayout(new GridLayout(1, false));

		vocabularyList = new TableViewerBuilder(composite);
		tableViewer = vocabularyList.getTableViewer();
		table = vocabularyList.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		TableViewerColumn tblclSentence = vocabularyList
				.createColumn("Vocabulary").bindToProperty("vocabulary")
				.setPercentWidth(25).build();

		TableViewerColumn tblclFurigana = vocabularyList
				.createColumn("Furigana").bindToProperty("furigana")
				.setPercentWidth(20).build();

		TableViewerColumn tblclHanViet = vocabularyList
				.createColumn("Han Viet").bindToProperty("hanviet")
				.setPercentWidth(15).build();

		TableViewerColumn tblclVnMeaning = vocabularyList
				.createColumn("Vietnamese meaning").bindToProperty("vnMeaning")
				.setPercentWidth(40).build();

		CommonUtils.vocabulariesHookDoubleClickCommand(tableViewer);

	}
	
	private void createCategoryToolBar(final Section section) {
		ToolBar toolbar = new ToolBar(section, SWT.FLAT);
		section.setTextClient(toolbar);

		ToolItem addItem = new ToolItem(toolbar, SWT.PUSH);
		addItem.setImage(Activator.getImageDescriptor("/icons/add.gif")
				.createImage());
		addItem.setToolTipText("Add a Vocabulary to this Category");

		addItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				AddRelatedVocabularyDialog relatedVocabularyDialog = new AddRelatedVocabularyDialog(
						section.getShell(), commonServices);
				if (relatedVocabularyDialog.open() == Window.OK) {
					Set<Vocabulary> selectedVocabularies = relatedVocabularyDialog
							.getSelectedVocabularies();
					if (!selectedVocabularies.isEmpty()) {
						// update selected vocabulary to current category						
						currentCategory.getVocabularies().addAll(selectedVocabularies);
						commonServices.getCategoryDao()
								.merge(currentCategory);

						// update Category table
						m_bindingContext.updateModels();
						tableViewer.refresh();
						tableViewer.setSelection(new StructuredSelection(selectedVocabularies.toArray()));
					}
				}
			}
		});

		ToolItem removeItem = new ToolItem(toolbar, SWT.PUSH);
		removeItem.setImage(Activator.getImageDescriptor("/icons/delete.gif")
				.createImage());
		removeItem
				.setToolTipText("Remove selected Category that this vocabulary belong to");

		removeItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer
						.getSelection();
				Vocabulary selectedVocabulary = (Vocabulary) selection
						.getFirstElement();
				if(selectedVocabulary != null){
					boolean confirm = MessageDialog.openConfirm(section
							.getShell(), "Deleting confirmation!",
							"Are you sure you want to delete this Vocabulary from current Category?");
					if(confirm){
						// remove selected vocabulary to current category						
						currentCategory.getVocabularies().remove(selectedVocabulary);
						commonServices.getCategoryDao().merge(currentCategory);
					}
					
					m_bindingContext.updateModels();
					tableViewer.refresh();
				}
			}
		});
	}

	private void update() {
		// m_bindingContext = initDataBindings();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.forms.IDetailsPage#inputChanged(org.eclipse.jface.viewers
	 * .IStructuredSelection)
	 */
	public void selectionChanged(IFormPart part, ISelection selection) {
		IStructuredSelection ssel = (IStructuredSelection) selection;
		if (ssel.size() == 1) {
			currentCategory = (Category) ssel.getFirstElement();
			// Get the category with updated vocabularies list
			currentCategory = commonServices.getCategoryDao()
					.getCategoryWithVocabularies(currentCategory.getCategoryId());
			sctnNewSection.setText("Category: " + currentCategory.getCategoryName());
			m_bindingContext = initDataBindings();
		} else
			currentCategory = null;

		update();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.IDetailsPage#commit()
	 */
	public void commit(boolean onSave) {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.IDetailsPage#setFocus()
	 */
	public void setFocus() {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.IDetailsPage#dispose()
	 */
	public void dispose() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.IDetailsPage#isDirty()
	 */
	public boolean isDirty() {
		return false;
	}

	public boolean isStale() {
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.forms.IDetailsPage#refresh()
	 */
	public void refresh() {
		update();
	}

	public boolean setFormInput(Object input) {
		return false;
	}

	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		ObservableSetContentProvider setContentProvider = new ObservableSetContentProvider();
		IObservableMap[] observeMaps = PojoObservables
				.observeMaps(setContentProvider.getKnownElements(),
						Vocabulary.class, new String[] { "vocabulary",
								"furigana", "hanviet", "vnMeaning" });
		tableViewer
				.setLabelProvider(new ObservableMapLabelProvider(observeMaps));
		tableViewer.setContentProvider(setContentProvider);
		//
		IObservableSet vocabulariesInputObserveSet = BeanProperties.set(
				"vocabularies").observe(currentCategory);
		tableViewer.setInput(vocabulariesInputObserveSet);
		//
		return bindingContext;
	}
}
